#!/usr/bin/env python

# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

""" OAuth 2.0-like Resource Server Filter."""

import logging
import model
from lib.loggable import loggable
from lib import http
from lib import utils

__author__ = "Maciej Machulak"
__maintainer__ = "Maciej Machulak"
__email__ = "mmachulak@google.com"

__copyright__ = "Copyright 2011, Google Inc."
__license__ = "Apache License 2.0"
__version__ = "0.1"
__status__ = "Prototype"

def api_authz_required(scope):
  """Requires the API call to be authorized."""   

  def inner_api_authz_required(handler):

    @loggable('check_authz')    
    def check_authz(self,*args):

      logging.debug('required scope: %s' % scope)
      authz_header = self.request.headers.get(http.Header.authorization) 
      if authz_header is None:
        logging.debug('api call is not authorized')
        self.response.set_status(401)
        return
      logging.debug('authz header: %s' % authz_header)
      access_token = utils.get_token(authz_header)   
      if access_token is None:
        logging.debug('token is none')
        self.response.set_status(401)
        return
      authorization = model.Authorization.all().filter('access_token = ', access_token).get()
      if authorization is None:
        logging.debug('token is invalid')
        self.response.set_status(401)
        return 
      # TODO: check if token is expired
      if (scope in authorization.scopes) is False:
        logging.debug('token has insufficient scope')
        self.response.set_status(401)
        return     
      self.user = authorization.user
      self.application = authorization.application
      handler(self,*args)
    return check_authz
  
  return inner_api_authz_required